﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;

namespace System.Text
{
	public static class StringExternsion
	{
		public static int ToInt(this string str, int def = 0)
		{
			int result;
			if (!int.TryParse(str, out result))
			{
				return def;
			}
			return result;
		}

		public static double ToDouble(this string str, double def = 0.0)
		{
			double result;
			if (!double.TryParse(str, out result))
			{
				return def;
			}
			return result;
		}

		public static bool ToBool(this string str, bool def = false)
		{
			int num = 0;
			bool result;
			if (!bool.TryParse(str, out result))
			{
				return int.TryParse(str, out num) && num != 0;
			}
			return result;
		}

		public static T ToValue<T>(this string str, T defValue)
		{
			if (string.IsNullOrEmpty(str.Trim()))
			{
				return defValue;
			}
			T result;
			try
			{
				result = (T)((object)TypeDescriptor.GetConverter(typeof(T)).ConvertFrom(str));
			}
			catch (Exception)
			{
				result = defValue;
			}
			return result;
		}

		public static string Left(this string str, int length)
		{
			if (string.IsNullOrEmpty(str))
			{
				return string.Empty;
			}
			if (str.Length <= length)
			{
				return str;
			}
			return str.Substring(0, length);
		}

		public static string Right(this string str, int length)
		{
			if (string.IsNullOrEmpty(str))
			{
				return string.Empty;
			}
			if (str.Length <= length)
			{
				return str;
			}
			return str.Substring(str.Length - length);
		}

		public static string Join(this StringBuilder sb, string seperator)
		{
			if (sb == null)
			{
				return string.Empty;
			}
			List<string> list = new List<string>();
			for (int i = 0; i < sb.Length; i++)
			{
				list.Add(sb[i].ToString());
			}
			return string.Join(seperator, list.ToArray());
		}

		public static string Join(this IEnumerable<string> strs, string seperator)
		{
			if (strs == null || !strs.Any<string>())
			{
				return string.Empty;
			}
			return string.Join(seperator, strs.ToArray<string>());
		}

		public static string Format(this string format, params object[] args)
		{
			return string.Format(format, args);
		}

		public static void SaveToFile(this string contents, string fileName)
		{
			File.WriteAllText(fileName, contents);
		}

		public static string Upgrade(this string str)
		{
			string result = string.Format("{0}(1)", str);
			if (!str.EndsWith(")"))
			{
				return result;
			}
			int num = str.LastIndexOf('(');
			if (num == -1)
			{
				return result;
			}
			string s = str.Substring(num + 1, str.Length - num - 2);
			string arg = str.Substring(0, num);
			int num2 = 1;
			if (!int.TryParse(s, out num2))
			{
				return result;
			}
			return string.Format("{0}({1})", arg, num2 + 1);
		}
	}
}
